// pages/labor/publish/publish.js
const app = getApp()

Page({
  data: {
    formData: {
      jobTitle: '',
      location: '',
      workType: 'part-time',
      salary: '',
      description: '',
      urgent: false,
      requirements: '',
      qq: '',
      phone: '',
      wechat: '',
      requiredCount: 1,
      images: [] // 添加图片数组
    },
    locationOptions: ['校内', '校外', '线上', '市中心', '商业区'],
    uploadedImages: [], // 已上传的图片列表
  },

  onLoad(options) {
    // 初始化页面
    console.log('劳务发布页面参数:', options);
    
    // 获取传递的劳务类型信息
    if (options.typeId && options.typeName) {
      this.setData({
        'formData.typeId': options.typeId,
        'formData.typeName': decodeURIComponent(options.typeName)
      });
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: `发布${decodeURIComponent(options.typeName)}`
      });
    }
    
    this.loadUserContactInfo()
  },

  // 加载用户联系方式信息
  async loadUserContactInfo() {
    try {
      // 从全局数据或API获取用户信息
      const userInfo = app.globalData.userInfo
      if (userInfo) {
        this.setData({
          'formData.qq': userInfo.qq || '',
          'formData.phone': userInfo.phone || '',
          'formData.wechat': userInfo.wechat || ''
        })
      } else {
        // 如果没有全局用户信息，从API获取
        const result = await app.utils.request({
          url: '/auth/user/info',
          method: 'GET'
        })

        if (result.code === 200 && result.data) {
          this.setData({
            'formData.qq': result.data.qq || '',
            'formData.phone': result.data.phone || '',
            'formData.wechat': result.data.wechat || ''
          })
        }
      }
    } catch (error) {
      console.error('加载用户联系信息失败:', error)
    }
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail

    this.setData({
      [`formData.${field}`]: value
    })
  },


  onLocationChange(e) {
    const index = e.detail.value
    this.setData({
      'formData.location': this.data.locationOptions[index]
    })
  },


  onWorkTypeChange(e) {
    this.setData({
      'formData.workType': e.detail.value
    })
  },

  onUrgentChange(e) {
    this.setData({
      'formData.urgent': e.detail.value
    })
  },

  onChooseImage() {
    const maxCount = 3 - this.data.uploadedImages.length
    if (maxCount <= 0) {
      wx.showToast({
        title: '最多只能上传3张图片',
        icon: 'none'
      })
      return
    }

    wx.chooseImage({
      count: maxCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('选择的图片:', res.tempFilePaths)
        this.uploadImages(res.tempFilePaths)
      }
    })
  },

  // 上传图片到MinIO
  async uploadImages(filePaths) {
    wx.showLoading({ title: '上传中...' })
    
    try {
      const uploadPromises = filePaths.map(filePath => this.uploadSingleImage(filePath))
      const results = await Promise.all(uploadPromises)
      
      // 过滤掉上传失败的图片
      const successResults = results.filter(result => result.success)
      
      if (successResults.length > 0) {
        // 更新已上传图片列表
        const newImages = [...this.data.uploadedImages, ...successResults.map(r => r.data)]
        this.setData({
          uploadedImages: newImages,
          'formData.images': newImages.map(img => img.url)
        })
        
        wx.showToast({
          title: `成功上传${successResults.length}张图片`,
          icon: 'success'
        })
      }
      
      if (successResults.length < filePaths.length) {
        wx.showToast({
          title: '部分图片上传失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('上传图片失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 上传单张图片
  async uploadSingleImage(filePath) {
    try {
      // 直接上传到后端接口
      const uploadResult = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: app.globalData.baseUrl + '/upload/file',
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + (wx.getStorageSync('token') || '')
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 200 && data.data) {
                resolve({
                  success: true,
                  data: {
                    url: data.data.url,
                    key: data.data.key,
                    originalName: filePath.split('/').pop()
                  }
                })
              } else {
                reject(new Error(data.message || '上传失败'))
              }
            } catch (e) {
              reject(new Error('解析上传结果失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })

      return uploadResult
    } catch (error) {
      console.error('上传单张图片失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  // 删除图片
  onDeleteImage(e) {
    const { index } = e.currentTarget.dataset
    const newImages = [...this.data.uploadedImages]
    newImages.splice(index, 1)
    
    this.setData({
      uploadedImages: newImages,
      'formData.images': newImages.map(img => img.url)
    })
  },

  // 预览图片
  onPreviewImage(e) {
    const { index, urls } = e.currentTarget.dataset
    const imageUrls = urls.map(item => item.url)
    
    wx.previewImage({
      current: imageUrls[index],
      urls: imageUrls
    })
  },

  validateForm() {
    const { formData } = this.data

    if (!formData.jobTitle.trim()) {
      wx.showToast({ title: '请输入工作标题', icon: 'none' })
      return false
    }


    if (!formData.location) {
      wx.showToast({ title: '请选择工作地点', icon: 'none' })
      return false
    }


    if (!formData.salary || formData.salary <= 0) {
      wx.showToast({ title: '请输入有效的薪资', icon: 'none' })
      return false
    }

    if (!formData.description.trim()) {
      wx.showToast({ title: '请输入工作描述', icon: 'none' })
      return false
    }

    if (!formData.requirements.trim()) {
      wx.showToast({ title: '请输入任职要求', icon: 'none' })
      return false
    }

    // 验证联系方式 - 至少填写一项
    if (!formData.qq.trim() && !formData.phone.trim() && !formData.wechat.trim()) {
      wx.showToast({ title: '请至少填写一种联系方式', icon: 'none' })
      return false
    }

    return true
  },

  async onSubmit() {
    if (!this.validateForm()) {
      return
    }

    wx.showLoading({ title: '发布中...' })

    try {
      const { formData } = this.data
      
      // 调试日志：检查typeId是否正确传递
      console.log('发布劳务数据:', {
        typeId: formData.typeId,
        typeName: formData.typeName,
        jobTitle: formData.jobTitle
      });

      const result = await app.utils.request({
        url: '/labor/publish',
        method: 'POST',
        data: {
          jobTitle: formData.jobTitle,
          location: formData.location,
          workType: formData.workType,
          salary: parseFloat(formData.salary),
          description: formData.description,
          requirements: formData.requirements,
          contactInfo: this.formatContactInfo(formData.qq, formData.phone, formData.wechat),
          qq: formData.qq,
          phone: formData.phone,
          wechat: formData.wechat,
          urgent: formData.urgent ? 1 : 0,
          requiredCount: formData.requiredCount,
          typeId: formData.typeId ? parseInt(formData.typeId) : null, // 添加劳务类型ID，确保是数字
          images: formData.images ? formData.images.join(',') : null // 添加图片数据，用逗号分隔
        }
      })

      wx.hideLoading()

      if (result.code === 200) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              // 跳转到劳务列表页面并自动刷新
              wx.reLaunch({
                url: '/pages/labor/list/list?refresh=true'
              })
            }, 1500)
          }
        })
      } else {
        throw new Error(result.message || '发布失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('发布劳务失败:', error)
      app.utils.showError(error.message || '发布失败')
    }
  },

  // 格式化联系方式信息
  formatContactInfo(qq, phone, wechat) {
    const contacts = []
    if (qq && qq.trim()) {
      contacts.push(`QQ: ${qq.trim()}`)
    }
    if (phone && phone.trim()) {
      contacts.push(`手机: ${phone.trim()}`)
    }
    if (wechat && wechat.trim()) {
      contacts.push(`微信: ${wechat.trim()}`)
    }
    return contacts.join(' | ')
  }

})
